"""
闹钟程序主入口
"""
import tkinter as tk
from tkinter import messagebox
import threading
from datetime import datetime, timedelta

from alarm_manager import AlarmManager
from audio_controller import AudioController
from ui import AlarmClockUI


class AlarmClockApp:
    def __init__(self):
        """初始化闹钟应用程序"""
        self.root = tk.Tk()
        
        # 初始化管理器
        self.alarm_manager = AlarmManager()
        self.audio_controller = AudioController()
        
        # 初始化UI
        self.ui = AlarmClockUI(self.root, self.alarm_manager, self.audio_controller)
        
        # 闹钟状态
        self.is_alarm_playing = False
        self.current_alarm_window = None
        
        # 启动闹钟检查
        self.alarm_manager.start_checking(self.on_alarm_triggered)
        
        # 设置窗口关闭处理
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        
        # 检查并创建默认铃声
        self.check_ringtones()
    
    def check_ringtones(self):
        """检查是否有铃声，如果没有则创建默认铃声"""
        ringtones = self.audio_controller.get_available_ringtones()
        if not ringtones:
            result = messagebox.askyesno(
                "提示",
                "检测到铃声库为空。\n\n是否创建默认铃声？\n（需要numpy和scipy库）\n\n点击'否'将打开铃声管理，您可以手动添加MP3/WAV文件。"
            )
            
            if result:
                if self.audio_controller.create_default_ringtone():
                    messagebox.showinfo("成功", "默认铃声已创建")
                    self.ui.refresh_alarm_list()
                else:
                    messagebox.showwarning(
                        "提示",
                        "无法创建默认铃声。\n\n请手动添加MP3或WAV文件到ringtones文件夹，\n或通过'管理铃声'按钮添加。"
                    )
                    self.ui.manage_ringtones()
            else:
                self.ui.manage_ringtones()
    
    def on_alarm_triggered(self, alarm):
        """闹钟触发回调"""
        if self.is_alarm_playing:
            return
        
        self.is_alarm_playing = True
        
        # 在新线程中播放闹钟
        threading.Thread(target=self.play_alarm, args=(alarm,), daemon=True).start()
    
    def play_alarm(self, alarm):
        """播放闹钟"""
        try:
            # 获取当前音量设置
            volume = self.ui.get_alarm_volume()
            
            # 设置系统音量
            self.audio_controller.set_system_volume(volume)
            
            # 播放铃声（循环播放）
            success = self.audio_controller.play_ringtone(alarm["ringtone"], volume, loop=True)
            
            if success:
                # 显示闹钟通知窗口
                self.root.after(0, lambda: self.show_alarm_notification(alarm))
            else:
                self.is_alarm_playing = False
                self.root.after(0, lambda: messagebox.showerror("错误", "播放闹钟失败"))
                
        except Exception as e:
            print(f"播放闹钟错误: {e}")
            self.is_alarm_playing = False
    
    def show_alarm_notification(self, alarm):
        """显示闹钟通知窗口"""
        if self.current_alarm_window:
            return
        
        notification = tk.Toplevel(self.root)
        self.current_alarm_window = notification
        
        notification.title("⏰ 闹钟提醒")
        notification.geometry("500x300")
        notification.resizable(False, False)
        notification.attributes('-topmost', True)
        notification.grab_set()
        
        # 居中显示
        notification.update_idletasks()
        x = (notification.winfo_screenwidth() // 2) - (notification.winfo_width() // 2)
        y = (notification.winfo_screenheight() // 2) - (notification.winfo_height() // 2)
        notification.geometry(f"+{x}+{y}")
        
        # 设置背景色
        notification.configure(bg="#ecf0f1")
        
        # 内容框架
        content_frame = tk.Frame(notification, bg="#ecf0f1")
        content_frame.pack(expand=True, fill="both", padx=20, pady=20)
        
        # 标题
        tk.Label(content_frame, text="⏰ 闹钟时间到！", 
                font=("Microsoft YaHei", 24, "bold"), 
                fg="#e74c3c", bg="#ecf0f1").pack(pady=20)
        
        # 时间信息
        time_str = f"{alarm['hour']:02d}:{alarm['minute']:02d}"
        tk.Label(content_frame, text=f"时间: {time_str}", 
                font=("Microsoft YaHei", 18), 
                fg="#2c3e50", bg="#ecf0f1").pack(pady=10)
        
        # 重复模式信息
        repeat_info = alarm['repeat']
        if repeat_info == "自定义":
            repeat_info += f" ({', '.join(alarm['custom_days'])})"
        
        tk.Label(content_frame, text=f"重复: {repeat_info}", 
                font=("Microsoft YaHei", 12), 
                fg="#7f8c8d", bg="#ecf0f1").pack(pady=5)
        
        # 铃声信息
        tk.Label(content_frame, text=f"🎵 {alarm['ringtone']}", 
                font=("Microsoft YaHei", 10), 
                fg="#3498db", bg="#ecf0f1").pack(pady=5)
        
        # 按钮框架
        button_frame = tk.Frame(content_frame, bg="#ecf0f1")
        button_frame.pack(pady=30)
        
        def stop_alarm():
            """停止闹钟"""
            self.audio_controller.stop_ringtone()
            self.audio_controller.restore_system_volume()
            self.is_alarm_playing = False
            self.current_alarm_window = None
            notification.destroy()
        
        def snooze_alarm():
            """稍后提醒"""
            self.audio_controller.stop_ringtone()
            self.audio_controller.restore_system_volume()
            self.is_alarm_playing = False
            self.current_alarm_window = None
            notification.destroy()
            
            # 创建5分钟后的提醒
            self.alarm_manager.create_snooze_alarm(alarm, snooze_minutes=5)
            self.ui.refresh_alarm_list()
            
            messagebox.showinfo("稍后提醒", "将在5分钟后再次提醒您")
        
        # 关闭按钮
        tk.Button(button_frame, text="✅ 关闭闹钟", command=stop_alarm,
                 width=18, height=2, bg="#27ae60", fg="white",
                 font=("Microsoft YaHei", 12, "bold"),
                 relief=tk.RAISED, bd=3).pack(side="left", padx=10)
        
        # 稍后提醒按钮
        tk.Button(button_frame, text="⏰ 稍后提醒 (5分钟)", command=snooze_alarm,
                 width=18, height=2, bg="#f39c12", fg="white",
                 font=("Microsoft YaHei", 12, "bold"),
                 relief=tk.RAISED, bd=3).pack(side="left", padx=10)
        
        # 处理窗口关闭
        notification.protocol("WM_DELETE_WINDOW", stop_alarm)
        
        # 让窗口闪烁以引起注意
        self.flash_window(notification, 5)
    
    def flash_window(self, window, count):
        """让窗口闪烁"""
        if count > 0 and window.winfo_exists():
            try:
                # 切换topmost属性来产生闪烁效果
                current = window.attributes('-topmost')
                window.attributes('-topmost', not current)
                window.after(500, lambda: self.flash_window(window, count - 1))
            except:
                pass
    
    def on_closing(self):
        """处理窗口关闭"""
        if self.is_alarm_playing:
            result = messagebox.askyesno(
                "确认退出",
                "闹钟正在响铃，确定要退出吗？\n\n退出后闹钟将停止播放。"
            )
            if not result:
                return
            
            # 停止闹钟
            self.audio_controller.stop_ringtone()
            self.audio_controller.restore_system_volume()
        
        # 停止闹钟检查
        self.alarm_manager.stop_checking()
        
        # 关闭窗口
        self.root.destroy()
    
    def run(self):
        """运行应用程序"""
        self.root.mainloop()


def main():
    """主函数"""
    try:
        app = AlarmClockApp()
        app.run()
    except Exception as e:
        print(f"程序错误: {e}")
        import traceback
        traceback.print_exc()
        input("按回车键退出...")


if __name__ == "__main__":
    main()
